import {
	useStore
} from "vuex";
import {
	ref,
	computed
} from "vue";
import {
	checkLogin,
	navBack,
	navTo,
	showSuccess,
	showToast
} from "@/core/app";
import {
	onLoad
} from "@dcloudio/uni-app";
import {
	sendSms
} from "@/api/login";
import { bindParent, bindingWx } from "@/api/user";

export const useIndex = () => {
	// 按钮样式
	const buttonStyle = {
		height: "100rpx",
		borderRadius: "16rpx",
		fontWeight: "bold",
		border: "none",
	};
	const navToPage = ref("pages/find-car/index");
	onLoad(async (options) => {
		if (checkLogin()) return navTo("pages/find-car/index", {}, "redirectTo");
		if (options.page) navToPage.value = options.page;
		if (process.env.NODE_ENV !== "production") {
			loginForm.value.data.phone = '15086962142'
			loginForm.value.data.code = '147258'
			check.value[0] = true;
		}
	});
	// 隐私政策同意
	const check = ref([false]);
	const showPopup = ref(false);
	const agreePolicy = () => {
		check.value[0] = true;
		showPopup.value = false;
	};
	const checkReadPolicy = () => {
		if (!check.value[0]) {
			showPopup.value = true;
			return false;
		} else {
			return true;
		}
	};
	// 登录表单
	const formRef = ref(null)
	const loginForm = ref({
		data: {
			phone: "",
			code: "",
			type: 'code', //登录类型 code：验证码登录 mobile:：app一键登录 wx_applet:：微信一键登录 wx_app：app微信登录
		},
	});
	const formRules = {
		"data.phone": {
			required: true,
			type: "string",
			message: "请输入手机号码",
			trigger: ["change", "blur"],
		},
		"data.code": {
			required: true,
			type: "string",
			message: "请输入验证码",
			trigger: ["blur", "change"],
		},
	};
	const tips = ref("");
	const uCodeRef = ref(null);
	const getCode = async () => {
		if (uCodeRef.value.canGetCode) {
			if (!loginForm.value.data.phone) return showToast("请输入手机再点击发送");
			showToast("正在获取验证码", "loading");
			let res = await sendSms({
				phone: loginForm.value.data.phone,
			});
			if (res) {
				uni.hideLoading();
				showToast("验证码已发送");
				uCodeRef.value.start();
			}
		} else {
			showToast("倒计时结束后再发送");
		}
	};

	// 登录
	const store = useStore();
	const tapLogin = async () => {
		if (!checkReadPolicy()) return;
		formRef.value.validate().then(async valid => {
			if (valid) {
				let result = await store.dispatch("LoginH5", loginForm.value.data);
				if (result) {
					showSuccess(result.msg);
					setTimeout(() => {
						if (!result.data.parent_id) {
							inviteOpen.value = true
							return
						}
						if (navToPage.value) navTo(navToPage.value, null, "redirectTo");
						else navBack();
					}, 500);
				}
			}
		}).catch(() => {})
	};

	/* 微信登录 */
	async function onLoginWechat(e) {
		if (!checkReadPolicy()) return;
		const data = {}
		data.js_code = await getJsCode()
		if (e) {
			data.code = e.detail.code;
		}
		let result = await store.dispatch("LoginWX", data);
		if (result) {
			showSuccess("登录成功")
			setTimeout(() => {
				if (!result.data.parent_id) {
					inviteOpen.value = true
					return
				}
				if (navToPage.value) navTo(navToPage.value, null, "redirectTo");
				else navBack();
			}, 500);
		}
	}

	/* 邀请码弹窗控制 */
	const inviteOpen = ref(false)
	const inviteCode = ref('')

	function setInviteCode() {
		if (!inviteCode.value) return showToast("请输入邀请码")
		bindParent({
			code: inviteCode.value
		}).then(res => {
			if (res.code === 200) {
				showSuccess('绑定成功！')
				inviteOpen.value = false
				inviteCode.value = ''
				setTimeout(() => {
					if (navToPage.value) navTo(navToPage.value, null, "redirectTo");
					else navBack();
				}, 500);
			}
		})
	}

	function skipInvite() {
		inviteOpen.value = false
		setTimeout(() => {
			if (navToPage.value) navTo(navToPage.value, null, "redirectTo");
			else navBack();
		}, 500);
	}

	/* 获取Jscode */
	function getJsCode() {
		return new Promise((resolve, reject) => {
			uni.login({
				success: (e) => {
					resolve(e.code)
				}
			})
		})
	}


	return {
		buttonStyle,
		check,
		agreePolicy,
		showPopup,
		formRef,
		loginForm,
		formRules,
		tips,
		uCodeRef,
		getCode,
		tapLogin,
		onLoginWechat,
		inviteOpen,
		inviteCode,
		setInviteCode,
		skipInvite
	};
};